﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Windows.Resources;
using System.Linq;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml;

namespace TAXILISM.Class
{
    public class CallTaxiNumber
    {
        public List<TaxiList> taxi_list = new List<TaxiList>();
        public int cnt_client, cnt_client2;
        public void feedTaxi()
        {
            taxi_list.Clear();
            XElement elm;

            StreamResourceInfo xml = Application.GetResourceStream(new Uri("TaxiPhone.xml", UriKind.Relative));
            elm = XElement.Load(xml.Stream);

            var TaxProfile = from taxi in elm.Descendants("Taxi")
                          select new TaxiList
                          {
                              Data_id = taxi.Element("id").Value,
                              Data_taxName = taxi.Element("name").Value,
                              Data_taxPhone = taxi.Element("phone").Value,
                              rate = 0,
                              numRate="No Rating"
                          };
            var taxlist = from t in TaxProfile
                          orderby t.rate descending
                               select t;
            foreach (TaxiList rs in taxlist) {
                taxi_list.Add(rs);
            }

        }

        public void putRecent(int id)
        {
            string fileName = "taxrecent.xaml";

            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, myIsolatedStorage))
                {
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent = true;
                    using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
                    {
                        writer.WriteStartElement("taxirecent");
                        writer.WriteStartElement("id");
                        writer.WriteString(id.ToString());
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                        writer.WriteEndDocument();
                        writer.Flush();
                    }
                }
            }         
        }

        public List<TaxiList> taxRecent = new List<TaxiList>();
        public List<TaxiList> taxVoteable = new List<TaxiList>();
        //public int idRecent;
        public void getRecent()
        {
            taxRecent.Clear();
            List<int> idList = new List<int>();
            try
            {
                IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("taxrecent.xaml", FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fileStream))
                {   
                    XElement eld = XElement.Parse(reader.ReadToEnd());
                    while (eld.FirstNode as XElement != null)
                    {
                        int idAdd = Convert.ToInt32((eld.FirstNode as XElement).Value);
                        (eld.FirstNode as XElement).Remove();
                        idList.Add(idAdd);
                    }
                }
            }
            catch (Exception)
            {
            }

            for (int i = 0; i < taxi_list.Count; i++)
                if (idList.Contains(Convert.ToInt32(taxi_list[i].Data_id)))
                {
                    //idRecent = i;
                    taxRecent.Add(taxi_list[i]);
                }
            
        }

        public void clearRecent() 
        {
            string fileName = "taxrecent.xaml";
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, myIsolatedStorage))
                {
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent = true;
                    using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
                    {
                        writer.WriteStartElement("taxirecent");
                        writer.WriteEndElement();
                        // Ends the document
                        writer.WriteEndDocument();
                        // Write the XML to the file.
                        writer.Flush();
                    }
                }
                //}
            }
        }

        public void getRateShow()
        {
            taxi_list.Clear();

            //TaxiServerOnServer.Service1SoapClient proxy = new TaxiServerOnServer.Service1SoapClient();
            //proxy.getDataAsync();
            //proxy.getDataCompleted += new EventHandler<TaxiServerOnServer.getDataCompletedEventArgs>(proxy_getDataCompleted);

            TaxiWebService.Service1SoapClient proxy = new TAXILISM.TaxiWebService.Service1SoapClient();
            proxy.getDataAsync();
            proxy.getDataCompleted += new EventHandler<TaxiWebService.getDataCompletedEventArgs>(proxy_getDataCompleted);
            

            cnt_client++;
        }

        void proxy_getDataCompleted(object sender, TAXILISM.TaxiServerOnServer.getDataCompletedEventArgs e)
        {

            var TaxProfile = from taxi in e.Result.Descendants("taxi")
                             select new TaxiList
                             {
                                 Data_id = taxi.Element("taxi_id").Value,
                                 Data_taxName = taxi.Element("taxi_name").Value,
                                 Data_taxPhone = taxi.Element("taxi_phone").Value,
                                 rate = Int32.Parse(taxi.Element("taxi_rate").Value),
                                 numRate = taxi.Element("taxi_ratecount").Value,
                                 //vote = taxi.Element("taxi_voteable").Value,
                                 rating = Decimal.Parse(taxi.Element("taxi_rating").Value),
                             };


            var taxlist = from t in TaxProfile
                          orderby t.rating descending
                          select t;
            double ratecheck;
            string numratecheck;
            foreach (TaxiList rs in taxlist)
            {

                numratecheck = rs.numRate;

                if (numratecheck.Equals("0"))
                {
                    rs.numRate = "No Rating";
                    ratecheck = 0;
                }
                else
                {
                    ratecheck = Convert.ToDouble(rs.rate) / Convert.ToDouble(numratecheck);
                    ratecheck = ((ratecheck % 1) >= 0.5) ? Math.Ceiling(ratecheck) : Math.Floor(ratecheck);
                }
                rs.noRate = ratecheck == 0 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                rs.oneRate = ratecheck == 1 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                rs.twoRate = ratecheck == 2 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                rs.threeRate = ratecheck == 3 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                rs.fourRate = ratecheck == 4 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                rs.fiveRate = ratecheck == 5 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;

                rs.numRate = rs.numRate + "Ratings";

                foreach (TaxiList vote in taxVoteable)
                {
                    if (rs.Data_id == vote.Data_id)
                    {
                        rs.voteable = System.Windows.Visibility.Visible;
                        break;
                    }
                    else
                    {
                        rs.voteable = System.Windows.Visibility.Collapsed;
                    }
                }

                taxi_list.Add(rs);
            }
            cnt_client--;
        }

        void proxy_getDataCompleted(object sender, TAXILISM.TaxiWebService.getDataCompletedEventArgs e)
        {
            
            var TaxProfile = from taxi in e.Result.Descendants("taxi")
                             select new TaxiList
                             {
                                 Data_id = taxi.Element("taxi_id").Value,
                                 Data_taxName = taxi.Element("taxi_name").Value,
                                 Data_taxPhone = taxi.Element("taxi_phone").Value,
                                 rate = Int32.Parse(taxi.Element("taxi_rate").Value),
                                 numRate = taxi.Element("taxi_ratecount").Value,
                                 //vote = taxi.Element("taxi_voteable").Value,
                                 rating = Decimal.Parse(taxi.Element("taxi_rating").Value),
                             };


            var taxlist = from t in TaxProfile
                          orderby t.rating descending
                          select t;
            double ratecheck;
            string numratecheck;
            foreach (TaxiList rs in taxlist)
            {
                
                numratecheck = rs.numRate;

                if (numratecheck.Equals("0"))
                {
                    rs.numRate = "No Rating";
                    ratecheck = 0;
                }
                else if (rs.numRate == "1")
                {
                    rs.numRate = rs.numRate + " Rating";
                    ratecheck = Convert.ToDouble(rs.rate) / Convert.ToDouble(numratecheck);
                    ratecheck = ((ratecheck % 1) >= 0.5) ? Math.Ceiling(ratecheck) : Math.Floor(ratecheck);
                }
                else 
                {
                    ratecheck = Convert.ToDouble(rs.rate) / Convert.ToDouble(numratecheck);
                    ratecheck = ((ratecheck % 1) >= 0.5) ? Math.Ceiling(ratecheck) : Math.Floor(ratecheck);
                    rs.numRate = rs.numRate + " Ratings";
                }
                rs.noRate = ratecheck == 0 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                rs.oneRate = ratecheck == 1 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                rs.twoRate = ratecheck == 2 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                rs.threeRate = ratecheck == 3 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                rs.fourRate = ratecheck == 4 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                rs.fiveRate = ratecheck == 5 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;

                foreach (TaxiList vote in taxVoteable) 
                {
                    if (rs.Data_id == vote.Data_id)
                    {
                        rs.voteable = System.Windows.Visibility.Visible;
                        break;
                    }
                    else 
                    {
                        rs.voteable = System.Windows.Visibility.Collapsed;
                    }
                }

                taxi_list.Add(rs);
            }
            cnt_client--;
        }

        string readString = "";
        public void putVoteable(int id, string status) 
        {
            string fileName = "taxvoteable.xaml";
            List<int> idList = new List<int>();
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
            try
            {
                IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("taxvoteable.xaml", FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    XElement eld = XElement.Parse(reader.ReadToEnd());
                    while (eld.FirstNode as XElement != null)
                    {
                        int idAdd = Convert.ToInt32((eld.FirstNode as XElement).Value);
                        (eld.FirstNode as XElement).Remove();
                        idList.Add(idAdd);
                    }
                }
            }
            catch (Exception)
            {
            }
         
            using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, myIsolatedStorage))
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
                {
                    writer.WriteStartElement("taxivoteable");
                    if (readString != "")
                    {
                        if (!readString.Contains("<id>" + id + "</id>"))
                        {
                            writer.WriteStartElement("id");
                            writer.WriteString(id.ToString());
                            writer.WriteEndElement();
                        }
                    }
                    else 
                    {
                        writer.WriteStartElement("id");
                        writer.WriteString(id.ToString());
                        writer.WriteEndElement();
                    }
                    for (int i = 0; i < idList.Count; i++)
                    {
                        writer.WriteStartElement("id");
                        writer.WriteString(idList[i].ToString());
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                    writer.Flush();
                }
            }
            //} 
        }

        public void delVoteable(int id, string status)
        {
            string fileName = "taxvoteable.xaml";
            List<int> idList = new List<int>();
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
            try
            {
                IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("taxvoteable.xaml", FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    XElement eld = XElement.Parse(reader.ReadToEnd());
                    while (eld.FirstNode as XElement != null)
                    {
                        int idAdd = Convert.ToInt32((eld.FirstNode as XElement).Value);
                        (eld.FirstNode as XElement).Remove();
                        if (idAdd != id)
                            idList.Add(idAdd);
                    }
                }
            }
            catch (Exception)
            {
            }

            using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, myIsolatedStorage))
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
                {
                    writer.WriteStartElement("taxivoteable");

                    for (int i = 0; i < idList.Count; i++)
                    {
                        writer.WriteStartElement("id");
                        writer.WriteString(idList[i].ToString());
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                    writer.Flush();
                }
            }
            //} 
        }

        public void getVoteable() 
        {
            List<int> idList = new List<int>();
            try
            {
                IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("taxvoteable.xaml", FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    readString = reader.ReadToEnd();
                    XElement eld = XElement.Parse(readString);
                    while (eld.FirstNode as XElement != null)
                    {
                        int idAdd = Convert.ToInt32((eld.FirstNode as XElement).Value);
                        (eld.FirstNode as XElement).Remove();
                        idList.Add(idAdd);
                    }
                }
            }
            catch (Exception)
            {
            }
            taxVoteable = new List<TaxiList>();
            for (int i = 0; i < taxi_list.Count; i++)
                if (idList.Contains(Convert.ToInt32(taxi_list[i].Data_id)))
                {
                    //idRecent = i;
                    taxVoteable.Add(taxi_list[i]);
                }
            
        }

        //void proxy_putVoteCompleted(object sender, TAXILISM.TaxiWebService.putVoteCompletedEventArgs e)
        //{
        //    cnt_client2--;
        //}

        public void putRate(int id, int rate) 
        {
            //TaxiServerOnServer.Service1SoapClient proxy = new TaxiServerOnServer.Service1SoapClient();
            //proxy.putRateAsync(id, rate);
            //proxy.putRateCompleted += new EventHandler<TaxiServerOnServer.putRateCompletedEventArgs>(proxy_putRateCompleted);

            TaxiWebService.Service1SoapClient proxy = new TAXILISM.TaxiWebService.Service1SoapClient();
            proxy.putRateAsync(id, rate);
            proxy.putRateCompleted += new EventHandler<TaxiWebService.putRateCompletedEventArgs>(proxy_putRateCompleted);

            cnt_client2++;
        }

        void proxy_putRateCompleted(object sender, TAXILISM.TaxiServerOnServer.putRateCompletedEventArgs e)
        {
            cnt_client2--;
        }

        void proxy_putRateCompleted(object sender, TAXILISM.TaxiWebService.putRateCompletedEventArgs e)
        {
            cnt_client2--;
        }
    }
}

